package com.ycy.leetcode;

import org.junit.Test;

/**
 * 最大公共字符串前缀
 */
public class LongestCommonPrefixString {

  @Test
  public void test() {

    String[] target = {"abb", "abc"};

//    findZuiDaGongGongQianZhui(target);


    System.out.println(longestCommonPrefix(target));
  }

  public String longestCommonPrefix(String[] strs) {

    if (strs == null || strs.length == 0) return "";

    int length = strs[0].length();

    for (int i = 0; i < length; i++) {
      //i 当前对比字符下标

      for (int j = 0; j < strs.length; j++) {
        String curStrs = strs[j];
        //
        if (curStrs == null || curStrs.length() <= i || curStrs.charAt(i) != strs[0].charAt(i)) {
          return i <= 0 ? "" : strs[0].substring(0, i);
        }
      }


    }
    return strs[0];

  }

  public void findZuiDaGongGongQianZhui(String[] target) {

    String prefix = "";
    int index = 0;

    while (true) {

      boolean breakflag = false;

      String cur = "";
      for (int i = 0; i < target.length; i++) {
        System.out.println(i);
        String s = target[i];

        if (s.length() - 1 < index) {//长度达到了
          breakflag = true;
          break;
        }
        if (i == 0)
          //第一个字符串作为参考值
          cur = String.valueOf(s.charAt(index));
        else {
          if (cur.equals(String.valueOf(s.charAt(index)))) {

          } else {
            breakflag = true;
            break;
          }
        }

      }
      if (breakflag) break;
      prefix += cur;
      index++;
    }

    System.out.println(prefix);

  }


}
